class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def increasingBST(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        head = None
        stack = [root]
        while stack[-1].left:
            stack.append(stack[-1].left)
        while stack:
            node = stack.pop()
            if node.right:
                right_node = node.right
                while right_node:
                    stack.append(right_node)
                    right_node = right_node.left
            if not head:
                head = node
                out_node = head
            else:
                node.left = None
                node.right = None
                out_node.right = node
                out_node = node
        return head

